﻿using System;
using System.Collections.ObjectModel;
using System.Threading;

using Sunyi.Project.WebPoint.Common;
using Sunyi.Project.WebPoint.Configuration;
using Sunyi.Project.WebPoint.DataContract;
using Sunyi.Project.WebPoint.Resource;
using Sunyi.Project.WebPoint.ServiceAccess;

namespace Sunyi.Project.WebPoint.BusinessLogic
{
    public partial class RoleManager
    {
        private static Collection<Guid> defaultRoles = null;
        public static Collection<Guid> DefaultRoles
        {
            get
            {
                if (defaultRoles == null)
                {
                    defaultRoles = new Collection<Guid>();
                    string[] defaultRoleIds = SystemConfiguration.WebSite[WebPointGlobalConstant.UserDefaultRole].Split(WebPointGlobalConstant.Comma[0]);

                    Guid roleId = Guid.Empty;
                    RoleManager roleManager = new RoleManager();
                    foreach (string defaultRoleId in defaultRoleIds)
                    {
                        bool flag = Guid.TryParse(defaultRoleId, out roleId);
                        if (flag)
                        {
                            Role role = roleManager.Select(roleId);
                            flag = role != null;
                            if (flag) defaultRoles.Add(role.Id);
                        }

                        if (!flag)
                        {
                            Log log = new Log { Level = LogLevel.Warning.ToString(), Source = typeof(RoleManager).Name };
                            log.UserName = Thread.CurrentThread.Name;
                            log.Data = string.Format(PlatformResource.DefaultRoleNotFound, defaultRoleId);

                            Logger.Write(log);
                        }
                    }
                }

                return defaultRoles;
            }
        }

        public Role SelectByName(string roleName)
        {
            return controller.SelectByName(roleName);
        }

        public Collection<Role> SelectAll(bool fillRolePermisson = false)
        {
            Collection<Role> roles = controller.SelectAll(fillRolePermisson);

            return roles;
        }

        public void UploadRoleInfo(Role role)
        {
            var roleServiceProxy = new RoleServiceProxy();
            roleServiceProxy.UpdateRole(role);
        }

        public int SearchCount(string roleName, bool isActive)
        {
            return controller.SearchCount(roleName, isActive);
        }

        public Collection<Role> Search(string roleName, bool isActive, int pageIndex, int pageSize)
        {
            return controller.Search(roleName, isActive, pageIndex, pageSize);
        }
    }
}
